import re

from excutor.excutor import Excutor

class Inductance(Excutor):

    def __init__(self, data):
        super().__init__(data)
        self.inductance = r"电感"
    
    @staticmethod
    def Existence(data,inductance = r"电感"):
        return data[data['new_key'].str.contains(inductance)]['new_key'].count()
    
    #修改数据表
    def processingData(self):
        indexInductance = self.data[self.data['new_key'].str.contains(self.inductance)].index
        for index in indexInductance:
            newValueRef = self._get_new_value(index)
            self.data.loc[index,'new_value_ref'] = newValueRef
        return self.data
    
    #分析并处理old_value,返回new_value_ref
    def _get_new_value(self,index):
        oneRowData = self.data.loc[index]
        old_value = oneRowData["old_value"]
        numbers = re.findall('\.?[0-9]*,?[0-9]+\.?[0-9]*',old_value)
        numbers = [
            '0'+num 
            if num[0]=='.' else num.replace(',','') 
            for num in numbers
            ] 
        units = re.findall('[nNmµp]?H(?!z)',old_value)
        if not units:
            units = re.findall('[nNmµp]?H(?!z)',oneRowData['new_key'])
        if numbers:
            if 'Hz' in old_value:
                if units:
                    return numbers[0] + units[0]
                return numbers[0] + 'nH'
            if re.search(' - | ~ ',old_value):
                return old_value.replace('-','to').replace('~','to')
            if len(numbers) == 1:
                if units:
                    return numbers[0] + units[0]
                return self._add_unit(numbers[0],oneRowData)
            if len(numbers)>1:
                if '±' in old_value or '%' in old_value:
                    if not units:
                        return numbers[0] + 'nh'
                    return numbers[0] + units[0]
                numbers = list(set(numbers))
                numbers.sort(key=float)
                if units:
                    return ','.join([num + units[0] for num in numbers])
                return ','.join([num + 'µH' for num in numbers])
                                           
        return old_value
            

    # 将没有单位的电感值返回单位
    def _add_unit(self,number,oneRowData):
        cat = oneRowData["ty_category"]
        if cat == "共模扼流圈":
            return number + 'mH'
        fnumber = float(number)
        if fnumber >= 1:
            return number + 'H'
        if fnumber > 1e-4:
            return f'{round(fnumber*1e3,3)}mH'
        if fnumber > 1e-7:
            return f'{round(fnumber * 1e6,3)}μH'
        if fnumber > 1e-10:
            return f'{round(fnumber * 1e9,3)}nH'
        return number + f'{round(fnumber * 1e12,3)}pH'